package toutiao

import (
	"github.com/astaxie/beego/orm"
	"log"
	"time"
)

type DailyNum struct {
	Id      int64
	Date    time.Time `orm:"type(date)"`
	Keyword *Keyword  `orm:"rel(fk)"`
	Number  int
}

func (this *DailyNum) TableUnique() [][]string {
	return [][]string{
		[]string{"Keyword", "Date"},
	}
}

func DailyNumIncrement(key *Keyword) {
	o := orm.NewOrm()

	loc, _ := time.LoadLocation("Asia/Shanghai")
	tt := time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, loc)

	dailyNum := &DailyNum{
		Keyword: key,
		Date:    tt,
		Number:  1,
	}

	if created, id, err := o.ReadOrCreate(dailyNum, "Keyword", "Date"); err == nil {
		if !created {
			sql := "UPDATE daily_num SET number = number + 1 WHERE id = ?"
			_, err := o.Raw(sql, id).Exec()
			if err != nil {
				log.Println(err)
			}
		}
	}
}
